<template>
  <el-affix :offset="0">
    <div class="bar">
      <router-link to="/">
        <div class="navi-logo">
          <img :src="interviewIcon" style="width:45px;margin-top:auto;"/>
        </div>
      </router-link>

      <div class="navi-user-and-search">

        <!-- 登录后才进行显示的组件 -->
        <div v-if="userStore.token !== ''" class="login-show">

          <!-- 用户头像触发按钮 -->
          <el-popover placement="bottom" :width="300" trigger="click">
            <template #reference>
              <el-button text style="margin-top:12px;" class="avatar" @click="fetchUserInfo">
                <el-avatar :src="userStore.user.userAvatar" class="avatar-pic"/>
              </el-button>
            </template>
            <el-row class="user-info-row">
              <el-button round size="small" color="#bc8711" plain class="el-col-4" style="margin:auto 10px auto 0;"
                         @click="edit_userInfo('userName')">edit</el-button>
              <el-text tag="b" class="el-col-9"> 用户名 </el-text>
              <el-text class="el-col-10"> {{ userStore.user.userName }}  </el-text>
            </el-row>
            <el-row class="user-info-row">
              <!--              TODO 按钮-->
              <el-button  round size="small" color="#0361a3" class="el-col-4" style="margin:auto 10px auto 0;" @click="pay">buy</el-button>
              <el-text tag="b" class="el-col-9"> GPT Token </el-text>
              <el-text class="el-col-10"> {{ userStore.user.userTokenCount }}  </el-text>
            </el-row>
          </el-popover>
        </div>
        <div class="login">
          <router-link to="/login" class="non-underline">
            <el-button round v-if="userStore.token === ''" size="large" class="login-button"> 登录 </el-button>
          </router-link>
          <el-button round v-if="userStore.token !== ''" @click="logout" size="large" class="login-button"> 登出 </el-button>
        </div>
      </div>
    </div>
  </el-affix>



</template>

<script lang="ts" setup>

import { useUserStore } from "@/stores/user";
import axios from "axios";
import {  reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import router from "@/router";



const userStore = reactive(useUserStore())

const pay = () => {
  router.push('/pay');
};

function logout() {
  axios.get('/gpt/logout')
      .then(function (response) {
        if (response.data.code === 200) {
          userStore.$patch({token: ''})
          localStorage.clear()
          alert("退出成功")
          router.push({
            name: 'login',
          })
        } else {
          alert('有错误')
        }
      })
}

function edit_userInfo() {
  let hint = ['Please input your user name', '修改用户名'];

  ElMessageBox.prompt(hint[0], hint[1], {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    inputPattern: /.+/,
    inputErrorMessage: '更改值不能为空!',
  })
      .then(({ value }) => {
        let payload = {
          userId: userStore.user.userId,  // 确保 userId 是正确的
          userName: value
        };
        axios.put('/gpt/userInfo', payload)
            .then(function (response) {
              console.log(response);  // 打印响应以检查返回数据
              if (response.data.code === 200) {
                userStore.$patch({ user: response.data.data });
                localStorage.setItem("user", JSON.stringify(response.data.data));
                ElMessage({
                  message: '修改成功',
                  type: 'success',
                });
              } else {
                ElMessage({
                  message: '修改失败.',
                  type: 'error',
                });
              }
            })
            .catch((error) => {
              console.error(error);  // 打印错误信息
              ElMessage({
                type: 'error',
                message: '请求失败: ' + error.message,
              });
            });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Input canceled',
        });
      });
}


function fetchUserInfo() {
  // 准备包含用户信息的查询参数
  const userId = userStore.user.userId;

  axios.get('/gpt/getUserInfo', {
    params: {
      userId: userId
    }
  })
      .then(function (response) {
        if (response.data.code === 200) {
          userStore.$patch({ user: response.data.data });
          localStorage.setItem("user", JSON.stringify(response.data.data));
        } else {
          ElMessage({
            message: '获取用户信息失败',
            type: 'error',
          });
        }
      })
      .catch((error) => {
        console.error(error);
        ElMessage({
          type: 'error',
          message: '请求失败: ' + error.message,
        });
      });
}


//localstorage持久保持token
onMounted(() => {
  if (localStorage.getItem('token')) {
    userStore.$patch({token: localStorage.getItem('token')})
    userStore.$patch({user: JSON.parse(localStorage.getItem('user'))})
  }
})




</script>


<style scoped>
.bar {
  height: 56px;
  width: 100%;
  box-shadow:  2px 2px 5px #3b4858, 2px 2px 5px var(--md-sys-color-primary-container-light);
  display: flex;
  background-color: rgb(44,44,47);
}

.navi-logo{
  height: 100%;
  margin-right: auto;
  margin-left: 10px;
}



.non-underline{
  color: #222222;
  text-decoration: none;
}

.navi-user-and-search{
  display: flex;
  margin-left: auto;
  margin-right: 10px;
}



.login-show {
  display: flex;
  flex-direction: row;
}

.avatar{
  margin-left: 20px;
  margin-right: 20px;
  margin-top: 3%;
}

.avatar-pic{
  margin: auto;
}

.user-info-row {
  padding: 10px;
}

.user-info-row:hover {
  background-color: var(--md-sys-color-primary-container-light);
  border-radius: 5px;
}

.login{
  margin: auto;
}

.login-button{
  margin: auto;
  width: 100%;
  background: var(--md-sys-color-secondary-light);
  border-color: var(--md-sys-color-secondary-light);
  color: var(--md-sys-color-on-secondary-light);
  box-shadow: 1px 1px #eaeaea;
}



@media screen and (max-width: 768px) {
  .navi-list {
    display: none;
  }
}

</style>


